package vip.xiaonuo.common.redislook;

import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RedissonConfig {
    
    @Value("${spring.redis.host:127.0.0.1}")
    private String host;
    
    @Value("${spring.redis.port:6379}")
    private int port;
    
    @Value("${spring.redis.password:}")
    private String password;
    
    @Value("${spring.redis.database:0}")
    private int database;
    
    @Value("${spring.redis.timeout:3000}")
    private String timeoutString;
    
    // 将带单位的时间字符串(如"10s")转换为毫秒数
    private int parseTimeout() {
        if (timeoutString == null || timeoutString.isEmpty()) {
            return 3000; // 默认3秒
        }
        
        String value = timeoutString.trim().toLowerCase();
        try {
            // 如果只有数字，假定为毫秒
            if (value.matches("\\d+")) {
                return Integer.parseInt(value);
            }
            
            // 处理带有单位的时间值
            if (value.endsWith("ms")) {
                return Integer.parseInt(value.substring(0, value.length() - 2));
            } else if (value.endsWith("s")) {
                return Integer.parseInt(value.substring(0, value.length() - 1)) * 1000;
            } else if (value.endsWith("m")) {
                return Integer.parseInt(value.substring(0, value.length() - 1)) * 60 * 1000;
            }
            
            // 无法识别的格式，使用默认值
            return 3000;
        } catch (NumberFormatException e) {
            return 3000; // 解析失败时使用默认值
        }
    }
    
    @Bean
    public RedissonClient redissonClient() {
        Config config = new Config();
        config.useSingleServer()
              .setAddress("redis://" + host + ":" + port)
              .setPassword(password.isEmpty() ? null : password)
              .setDatabase(database)
              .setConnectionMinimumIdleSize(5)
              .setConnectionPoolSize(20)
              .setConnectTimeout(parseTimeout());
        
        return Redisson.create(config);
    }
}
